package com.geline.alisms;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class AliSmsSender implements SmsSender {
	private SmsClient client = null;
	private SendPostProcessor sendPostProcessor = null;
	private AliSmsProperties properties;

	public AliSmsSender(AliSmsProperties properties, SendPostProcessor sendPostProcessor) {
		this.properties = properties;
		this.client = new SmsClient(properties.getRegionId(), properties.getAccessKey(), properties.getSecretKey());
		this.sendPostProcessor = sendPostProcessor;
	}

	@Override
	public String channel() {
		return Constants.Channel.ALI;
	}

	@Override
	public SendResponse send(String mobile, String templateCode, Map<String, String> param) {
		String content = null;
		List<SmsTemplate> templates = this.properties.getTemplates();
		for (SmsTemplate template : templates) {
			if (template.getCode().equals(templateCode)) {
				content = template.getContent();
				break;
			}
		}
		if(content==null){
			throw new RuntimeException("未找到模板："+templateCode);
		}
		content = content.replaceAll("\\$\\{code\\}", param.get("code"));
		String signName = properties.getSignName();
		// AliSms的依赖包中含有gson，所以利用gson来处理
		String templateParamJson = JSONUtil.toJsonStr(param);
		SendResponse sendResponse = client.send(mobile, signName, templateCode, templateParamJson);
		log.debug("sendResponse : {}", sendResponse);
		log.info("[{}], [{}]:{}", mobile, signName, content);
		if (sendPostProcessor != null) {
			sendPostProcessor.afterSend(Constants.Channel.ALI, mobile, signName, content, sendResponse);
		}
		return sendResponse;
	}
}